package com.wang.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wang.auth.service.SysDeptService;
import com.wang.auth.service.SysPostService;
import com.wang.auth.service.SysRoleService;
import com.wang.auth.service.SysUserService;
import com.wang.common.result.Result;
import com.wang.model.system.SysDept;
import com.wang.model.system.SysUser;
import com.wang.model.system.dto.StatisticsDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author wjh
 * @create 2023-06-14
 */
@RestController
@RequestMapping("/admin/system/tongjitu")
public class TongJiTuController {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private SysPostService postService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("/allUser")
    public Result getAllUser(){
        StatisticsDto statisticsDto = new StatisticsDto();
        statisticsDto.setTotalUsers(userService.count());
        statisticsDto.setTotalRoles(roleService.count());
        statisticsDto.setTotalDepts(deptService.count());
        statisticsDto.setTotalPosts(postService.count());
        ArrayList<Integer> integers = new ArrayList<>();
        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 7; i >= 0; i--) {
            String date = LocalDateTime.now().plusDays(-1 * i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String cont = stringRedisTemplate.opsForValue().get("PV:" + date);
            if (StringUtils.isBlank(cont) || cont.equals("null")){
                integers.add(0);
                continue;
            }
            Integer value = Integer.valueOf(cont);
            integers.add(value);
        }
        statisticsDto.setPV(integers);
        List<SysDept> list = deptService.list();
        for (SysDept sysDept : list) {
            LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(SysUser::getDeptId,sysDept.getId());
            int count = userService.count(userLambdaQueryWrapper);
            map.put(sysDept.getName(), count);
        }
        statisticsDto.setDeptTotals(map);
        return Result.success(statisticsDto);
    }
}
